package mysql

import (
	"backend/models"
	"backend/utils/api"
	"backend/utils/snowflake"
	"crypto/md5"
	"encoding/hex"
	"go.uber.org/zap"
)

const secret = "miaokela" // 加密盐

func encryptPassword(data []byte) (result string) {
	h := md5.New()
	h.Write([]byte(secret))
	return hex.EncodeToString(h.Sum(data))
}

// Register 用户注册逻辑
func Register(user *models.User) (err error) {
	// 判断用户是否存在
	var count uint64
	if err = Orm.Model(user).Where("username = ?", user.Username).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return api.ErrorUserExit
	}

	// 通过雪花算法生成用户id
	userID, err := snowflake.GetID()

	if err != nil {
		zap.L().Error("生成Userid失败", zap.Error(err))
		return api.ErrorGenIDFailed
	}
	// 密码加密
	password := encryptPassword([]byte(user.Password))

	// 创建用户
	user.Password = password
	user.UserID = userID
	if err = Orm.Create(user).Error; err != nil {
		return err
	}
	return
}

// Login 用户登录逻辑
func Login(username, password string) (err error) {
	var user models.User
	password = encryptPassword([]byte(password))
	if err = Orm.Where("username = ? AND password = ?", username, password).First(&user).Error; err != nil {
		return err
	}
	return
}
